<?php
/**
 *
 *
 *
 */
abstract class Yz_Form_Parser_Abstract
    extends Yz_Class
    implements Yz_Form_Parser_Interface
{


    protected $errors = array();


    /**
     *  @param form
     *  @param ArrayAccess values to be parsed
     *  @return int number of errors
     */
    public function parse(Yz_Form_Interface $form, $values=null)
    {
        debug();
        // ensure values is a hash
        $values = new Yz_Hash($values);
        // error count
        $o = 0;
        foreach ($form->getElements() as $element) {
            // TODO callbacks
            try {
                $this->parseElement($element, $values);
            } catch (Yz_Form_Element_Exception $ex) {
                debug($ex->toString(true));
                $o ++;
            }
        }
        if ($o > 0) {
            throw new Yz_Form_Parser_Exception;
        }
        return $this;
    }

    /**
     *  these may be element-related as well as global
     */
    final public function getErrors()
    {
        return $this->errors;
    }


    protected function parseElement(Yz_Form_Element_Interface $element, Yz_Hash $values)
    {
        return $element->parse($values);
        /* ### OLD
        $callback = "parseElement_".$element->name;
        if (method_exists($this, $callback)) {
            return $this->$callback($element, $values);
        }
        return $this->parseElementDefault($element, $values);
        */
    }


    protected function parseElementDefault(Yz_Form_Element_Interface $element, Yz_Hash $values)
    {
        return $element->parse($values[$element->name]);
    }

}
